package com.king.juc.n8.threadpooldemo.timerdemo;

import lombok.extern.slf4j.Slf4j;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 线程池 - 定时任务
 *
 * @author king
 * @date 2020/12/12 15:46
 */
@Slf4j(topic = "c.ScheduledTest")
public class ScheduledTest {
    public static void main(String[] args) {
        // 每周四 18:00:00 定时执行任务

        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 每周时间
        long period = 1000 * 60 * 60 * 24 * 7;
        // 获取周四
        LocalDateTime time = now.withHour(18).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);
        log.debug("当前时间: {}, 周四: {}", now, time);

        // 判断当前时间大于周四
        if (now.compareTo(time) > 0){
            time = time.plusWeeks(1);
        }
        log.debug("当前时间: {}, 周四: {}", now, time);

        // 时间计算
        long initialDelay = Duration.between(now, time).toMillis();
        log.debug("时间间隔: {}", initialDelay);

        /**
         * initialDelay 代表当前时间和周四的时间差
         * period 一周的间隔时间
         */
        pool.scheduleAtFixedRate(() -> {}, initialDelay, period, TimeUnit.MILLISECONDS);
    }
}
